<!--
  * 生产BOM信息
  *
  * @Author:    lmabbe
  * @Date:      2025-06-27 19:00:37
  * @Copyright  lmabbe
-->
<template>
  <a-modal :destroyOnClose="true" :maskClosable="false" :open="visibleFlag" :title="form.bomId ? '编辑' : '添加'" :width="450" @cancel="onClose">
    <a-form ref="formRef" :label-col="{ span: 5 }" :model="form" :rules="rules">
      <a-form-item label="客户信息" name="belongCustomerCode">
        <a-select v-model:value="form.belongCustomerCode" :allowClear="true" :style="`width: 100%`" placeholder="请选择归属客户">
          <a-select-option v-for="item in customerData" :key="item.customerCode" :value="item.customerCode">
            {{ item.customerAbbreviation }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="成品/机型" name="materialCode">
        <TableSelect
          v-model:modelValue="form.materialCode"
          :columns="[
            { title: '成品/机型编号', dataIndex: 'materialCode', key: 'materialCode' },
            { title: '成品/机型名称', dataIndex: 'materialName', key: 'materialName' },
            { title: '成品/机型规格', dataIndex: 'materialSpec', key: 'materialSpec' },
            { title: '归属客户', dataIndex: 'belongCustomerAbbreviation', key: 'belongCustomerAbbreviation' },
          ]"
          :options="materialData"
          :placeholder="'输入物料编号/名称/规格'"
          @search="handleMaterialSearch"
          @select="handleMaterialSelect"
        />
      </a-form-item>
      <a-form-item label="BOM版本号" name="bomVer">
        <a-input v-model:value="form.bomVer" placeholder="BOM版本号" style="width: 100%" />
      </a-form-item>
      <a-form-item label="制程类型" name="processCategory">
        <DictSelect v-model:value="form.processCategory" dict-code="PROCESS_CATEGORY" placeholder="制程类型" width="100%" />
      </a-form-item>
      <a-form-item label="备注" name="remark">
        <a-textarea v-model:value="form.remark" placeholder="备注" style="width: 100%" />
      </a-form-item>
    </a-form>

    <template #footer>
      <a-space>
        <a-button @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">保存</a-button>
      </a-space>
    </template>
  </a-modal>
</template>
<script setup>
  import { nextTick, reactive, ref } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';

  import { bomInfoApi } from '/@/api/business/product/bom/bom-info-api.js';
  import { smartSentry } from '/@/lib/smart-sentry';
  import TableSelect from '/@/components/TableSelect/index.vue';
  import { materialInfoApi } from '/@/api/business/basic/material/material-info-api.js';
  import { customerInfoApi } from '/@/api/business/basic/customer/customer-info-api.js';
  import DictSelect from '/@/components/support/dict-select/index.vue';

  // ------------------------ 事件 ------------------------

  const emits = defineEmits(['reloadList']);

  // ------------------------ 显示与隐藏 ------------------------
  // 是否显示
  const visibleFlag = ref(false);
  const addFlag = ref(false);
  function show(rowData) {
    addFlag.value = !Object.prototype.hasOwnProperty.call(rowData, 'bomId');
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    customerAll();
    visibleFlag.value = true;
    nextTick(() => {
      formRef.value.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // ------------------------ 表单 ------------------------

  // 组件ref
  const formRef = ref();

  const formDefault = {
    bomId: undefined, //bom编号
    bomVer: undefined, //BOM版本号
    materialCode: undefined, //成品/机型编码
    materialName: undefined, //成品/机型名称
    materialSpec: undefined, //成品/机型规格
    materialDesc: undefined, //成品/机型描述
    processCategory: undefined, //制程类型
    belongCustomerCode: undefined,
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    bomVer: [{ required: true, message: 'BOM版本号 必填' }],
    materialCode: [{ required: true, message: '成品/机型编码 必填' }],
    //processCategory: [{ required: true, message: '制程类型 必填' }],
  };

  // 点击确定，验证表单
  async function onSubmit() {
    try {
      await formRef.value.validateFields();
      save();
    } catch (err) {
      message.error('参数验证错误，请仔细填写表单数据!');
    }
  }

  // 新建、编辑API
  async function save() {
    SmartLoading.show();
    try {
      if (!addFlag.value) {
        await bomInfoApi.update(form);
      } else {
        await bomInfoApi.add(form);
      }
      message.success('操作成功');
      emits('reloadList');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  const materialData = ref();

  const handleMaterialSelect = (value) => {
    form.materialCode = value.record.materialCode;
    form.materialSpec = value.record.materialSpec;
    form.materialName = value.record.materialName;
    form.materialDesc = value.record.materialDesc;
  };

  const handleMaterialSearch = (searchValue) => {
    let param = {
      keywords: searchValue,
      belongCustomer: form.belongCustomerCode,
      materialProperty: 'PRODUCT',
    };
    materialInfoApi.searchTop10(param).then((res) => {
      materialData.value = res.data;
    });
  };

  const customerData = ref();

  function customerAll() {
    customerInfoApi.customerAll().then((res) => {
      customerData.value = res.data;
    });
  }

  defineExpose({
    show,
  });
</script>
